package com.global.college.base.baselist;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;

/**
 * 类描述：底部Tab栏第二个对应的Fragment
 */
public abstract class HnViewPagerBaseFragment extends Fragment {

    public FragmentActivity mActivity;

    /**视图控件是否初始化完成*/
    protected boolean isViewInitiated;

    /**Fragment是否可见*/
    protected boolean isVisibleToUser;

    /**数据是否初始化完成*/
    public boolean isDataInitiated;

    public View rootView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = View.inflate(mActivity,getContentViewId(), null);
        ButterKnife.bind(this, rootView);
        initView(inflater,container,savedInstanceState);
        return rootView;
    }

    /**
     * this method must be implement by child activity, instead of setContentView in child activity
     */
    public abstract int getContentViewId();

    /**
     * 子类实现此抽象方法返回view进行展示
     *
     * @param inflater
     * @return
     */
    public abstract void initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    /**
     * lazy initialize data
     */
    public abstract void fetchData();

    /**
     * 当Fragment可见的时候所执行的方法
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    /**
     * prepare initialize data
     */
    private boolean prepareFetchData() {

        if (isVisibleToUser && isViewInitiated && (!isDataInitiated )) {
            fetchData();
            isDataInitiated = true;
            return true;
        }
        return false;
    }
    /**
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass
     */
    public void openActivity(Class<?> pClass) {
        Intent intent = new Intent();
        intent.setClass(mActivity, pClass);
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }



}
